<template>
  <div class="search-view">
    <app-header />
    
    <main class="container">
      <h1 style="margin-bottom: 20px;margin-top: 20px;">搜索表情包</h1>
      
      <search-bar 
        :is-loading="isLoading"
        :initial-value="searchQuery"
        @search="handleSearch"
      />
      
      <div v-if="searchPerformed" class="search-results-header">
        <h2 v-if="hasMemes">{{ searchResultsTitle }}</h2>
      </div>
      
      <meme-grid 
        :memes="memes"
        :is-loading="isLoading"
        :has-next-page="hasNextPage"
        :empty-message="'没有找到符合搜索条件的表情包'"
        @load-more="loadMore"
      />
    </main>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import AppHeader from '../components/AppHeader.vue'
import SearchBar from '../components/SearchBar.vue'
import MemeGrid from '../components/MemeGrid.vue'
import { searchMemes, searchMemesByTag } from '../api/memes'

const route = useRoute()
const router = useRouter()

const memes = ref([])
const isLoading = ref(false)
const page = ref(1)
const totalPages = ref(0)
const searchPerformed = ref(false)
const searchQuery = ref('')
const searchCategory = ref(null)
const searchSort = ref('trending')
const activeTag = ref('')

const hasMemes = computed(() => memes.value.length > 0)
const hasNextPage = computed(() => page.value < totalPages.value)

const searchResultsTitle = computed(() => {
  let title = '搜索结果'
  
  if (searchQuery.value) {
    title += ` - "${searchQuery.value}"`
  }
  
  if (searchCategory.value) {
    title += ` 分类：${searchCategory.value}`
  }
  
  return title
})

onMounted(() => {
  // 从URL查询获取搜索参数
  const queryParams = route.query
  
  if (queryParams.tag) {
    // 将tag参数转为搜索查询
    searchQuery.value = queryParams.tag
    activeTag.value = queryParams.tag
    performSearch()
  } else if (queryParams.query || queryParams.category || queryParams.sort) {
    searchQuery.value = queryParams.query || ''
    searchCategory.value = queryParams.category || null
    searchSort.value = queryParams.sort || 'trending'
    
    // 如果有query参数，也将其视为标签
    if (queryParams.query) {
      activeTag.value = queryParams.query
    }
    
    performSearch()
  }
})

watch(() => route.query, (newQuery) => {
  if (newQuery.tag !== undefined) {
    searchQuery.value = newQuery.tag
    activeTag.value = newQuery.tag
    performSearch()
  } else if (newQuery.query !== undefined || 
      newQuery.category !== undefined || 
      newQuery.sort !== undefined) {
    
    searchQuery.value = newQuery.query || ''
    searchCategory.value = newQuery.category || null
    searchSort.value = newQuery.sort || 'trending'
    
    // 如果有query参数，也将其视为标签
    if (newQuery.query) {
      activeTag.value = newQuery.query
    } else {
      activeTag.value = ''
    }
    
    performSearch()
  }
}, { deep: true })

function handleSearch(searchParams) {
  searchQuery.value = searchParams.query || ''
  searchCategory.value = searchParams.category || null
  searchSort.value = searchParams.sort || 'trending'
  
  // 如果有搜索关键词，将其视为标签搜索，并更新activeTag
  if (searchQuery.value) {
    activeTag.value = searchQuery.value
  } else {
    activeTag.value = ''
  }
  
  // 更新URL
  router.push({
    path: '/search',
    query: {
      ...(searchQuery.value && { query: searchQuery.value }),
      ...(searchCategory.value && { category: searchCategory.value }),
      ...(searchSort.value && { sort: searchSort.value })
    }
  })
  
  performSearch()
}

async function performSearch(resetPage = true) {
  if (resetPage) page.value = 1
  if (isLoading.value) return
  
  isLoading.value = true
  
  try {
    // 将普通搜索改为使用标签搜索
    const response = await searchMemes({
      query: searchQuery.value,
      page: page.value
    })
    
    // 确保我们从正确的属性获取数据
    const data = response.data
    const memeData = data.memes || []
    const pagination = data.pagination || { totalPages: 0 }
    
    if (resetPage) memes.value = memeData
    else memes.value = [...memes.value, ...memeData]
    
    totalPages.value = pagination.totalPages
    searchPerformed.value = true
    
    // 如果没有找到结果，给出提示
    if (memeData.length === 0 && resetPage) {
      console.log(`没有找到包含关键词 "${searchQuery.value}" 的表情包`)
    }
  } catch (error) {
    console.error('搜索失败:', error)
    
    // 演示用模拟数据
    const mockMemes = getMockMemes(12, searchQuery.value)
    
    if (resetPage) memes.value = mockMemes
    else memes.value = [...memes.value, ...mockMemes]
    
    totalPages.value = 3
    searchPerformed.value = true
  } finally {
    isLoading.value = false
  }
}

function loadMore() {
  if (hasNextPage.value && !isLoading.value) {
    page.value++
    performSearch(false)
  }
}

// 生成模拟表情包数据的辅助函数
function getMockMemes(count, query = '') {
  return Array.from({ length: count }, (_, i) => ({
    id: `mock-search-${i}`,
    title: query ? `包含 "${query}" 的表情包 ${i + 1}` : `搜索结果 ${i + 1}`,
    url: `https://picsum.photos/seed/search${i + 1}/400/300`,
    likes: Math.floor(Math.random() * 1000),
    views: Math.floor(Math.random() * 10000),
    tags: [query, '搞笑', '动物', '表情包'],
    createdAt: new Date(Date.now() - Math.floor(Math.random() * 1000000000)).toISOString()
  }))
}
</script>

<style scoped>
.search-view {
  min-height: 100vh;
  width: 100%;
}

.container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.search-results-header {
  margin: 20px 0;
}

.active-tag {
  display: inline-flex;
  align-items: center;
  background-color: #f0f0f0;
  padding: 8px 12px;
  border-radius: 50px;
  margin-top: 16px;
}

.tag-label {
  margin-right: 8px;
  font-weight: 500;
  color: #555;
}

.tag-name {
  font-weight: 600;
  color: #1976d2;
}

.clear-tag-btn {
  background: none;
  border: none;
  color: #555;
  font-size: 14px;
  cursor: pointer;
  margin-left: 8px;
  padding: 0 4px;
}

.clear-tag-btn:hover {
  color: #d32f2f;
}
</style> 